package com.hpin.mlxteacher.message;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.ImageAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.BitmapDetail;
import com.hpin.mlxteacher.bean.People;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.ActionSheetDialog;
import com.hpin.mlxteacher.widget.ActionSheetDialog.OnSheetItemClickListener;
import com.hpin.mlxteacher.widget.ActionSheetDialog.SheetItemColor;
import com.hpin.mlxteacher.widget.GridViewForScrollView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 编辑信息页面
 * Created by Aaron on 2015/7/20.
 */
public class EditActivity extends BaseActivity {

    /**
     * 分类code
     */
    private static final int CLASSIFY_CODE = 1007;
    /* 收件人code*/
    private static final int RECEIVER_CODE = 1008;
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 101;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 102;
    /* 分类*/
    private TextView tv_classify;
    private ImageView iv_delete_title;
    private EditText et_title;
    private GridViewForScrollView gv_photos;
    /*拍照的文件保存的位置*/
    private File currentFile;
//    //当前GridView展示的图片的集合
//    private ArrayList<String> currentShowPhotos = new ArrayList<String>();
    /**
     * 当前显示的有效图片的集合
     */
    private List<Bitmap> currentBitmaps;
    /**
     * Gridview 存放的图片的集合
     */
    private ArrayList<BitmapDetail> bitmapList;
    //用于添加有效图片的 + 号 图片
    private BitmapDetail addBitmapDeail;

    private ImageAdapter imageAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_edit);

        initWidget();

    }

    private void initWidget() {

//        currentShowPhotos.add(Constant.ADDBITMAPPATH);

        ImageView tv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_title.setText(getResources().getString(R.string.new_message));
        tv_right.setText(getResources().getString(R.string.send_message));

        tv_left.setOnClickListener(this);
        tv_right.setOnClickListener(this);

        tv_classify = (TextView) findViewById(R.id.tv_classify);
        iv_delete_title = (ImageView) findViewById(R.id.iv_delete_title);
        RelativeLayout rl_classify = (RelativeLayout) findViewById(R.id.rl_classify);
        RelativeLayout rl_receiver_people = (RelativeLayout) findViewById(R.id.rl_receiver_people);
        et_title = (EditText) findViewById(R.id.et_title);

        gv_photos = (GridViewForScrollView) findViewById(R.id.gv_photos);

        rl_classify.setOnClickListener(this);
        rl_receiver_people.setOnClickListener(this);
        iv_delete_title.setOnClickListener(this);

        et_title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                iv_delete_title.setVisibility(et_title.getText().toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
            }
        });


        initGrideView();

    }

    /**
     * 初始化GrideView
     */
    private void initGrideView() {

        bitmapList = new ArrayList<BitmapDetail>();

        //先添加 + 号图片
        Bitmap addBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_add);
        addBitmapDeail = new BitmapDetail(addBitmap, Constant.ADDBITMAPPATH);

        bitmapList.add(addBitmapDeail);
        imageAdapter = new ImageAdapter(this, bitmapList);
        gv_photos.setAdapter(imageAdapter);


        currentBitmaps = new ArrayList<Bitmap>();

        gv_photos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //点击的是图片的最后一个
                if (currentBitmaps.size() == 0 || currentBitmaps.size() == position) {
                    //添加照片 弹出选择对话框
                    showChoose();

                } else {
                    //查看照片


                }
            }
        });


    }


    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                //返回

                abandonEdit();

                break;
            case R.id.iv_delete_title:
                //删除录入的标题
                et_title.setText("");

                break;
            case R.id.tv_right:
                //发送


                break;
            case R.id.rl_classify:
                //分类
                Intent classifyIntent = new Intent(this, ClassifyActivity.class);
                startActivityForResult(classifyIntent, CLASSIFY_CODE);

                break;
            case R.id.rl_receiver_people:
                //收件人

                Intent intent = new Intent(this, ReceiverActivity.class);
                startActivityForResult(intent, RECEIVER_CODE);

                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //联系人
        if (resultCode == RECEIVER_CODE) {

            if (data == null)
                return;
            //获得到选中的接受人
            List<People> chooseedPeoples = (List<People>) data.getSerializableExtra("chooseedPeoples");

            if (chooseedPeoples == null || chooseedPeoples.size() < 1)
                return;

            for (People p : chooseedPeoples) {

                String name = p.name;

                LogUtil.e("TAG", "name==>" + name);
            }

        }

        //分类
        if (requestCode == CLASSIFY_CODE) {

            if (data == null)
                return;

            String classify = data.getStringExtra("classify");

            tv_classify.setText(classify);

        }

        //拍照
        if (requestCode == TAKE_PHOTO_CODE) {

            //压缩图片
            if (currentFile != null && currentFile.exists()) {
                commpressPic(currentFile.getPath());
            }
        }

        //选择照片
        if (requestCode == PHOTO_ALBUM_CODE) {
            if (data == null)
                return;

            //获取到传过来的图片的集合
            ArrayList<String> tempPhotos = data.getStringArrayListExtra("selectedPhotos");
            if (tempPhotos!=null && tempPhotos.size() > 0) {

                for(String path : tempPhotos) {

                    LogUtil.e("TAG", "返回回来的照片的路径==>" + path);

//                    //判断图片是否已经上传过,如果已经上传过就不需要再上传了
//                    if (currentShowPhotos.contains(path))
//                          continue;
//
//                    currentShowPhotos.add(path);
                    commpressPic(path);
                }

            }

        }
    }

//    public DeleteListener deleteListener;
//
//    interface DeleteListener {
//
//        public abstract void deletePhoto();
//
//    }


    /**
     * 压缩并 上传图片
     *
     * @param picturePath 图片存储的路径
     */
    private void commpressPic(String picturePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        // options 设为true时，构造出的bitmap没有图片，只有一些长宽等配置信息，但比较快，设为false时，才有图片
        options.inJustDecodeBounds = true;
        Bitmap b = BitmapFactory.decodeFile(picturePath, options);
        int scale = (int) (options.outWidth / (float) 300);
        if (scale <= 0)
            scale = 1;
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        b = BitmapFactory.decodeFile(picturePath, options);
//        BitmapFactory.decodeByteArray();
//        LogUtil.e("TAG", "ByteCount==>" + b.getByteCount());

        // 上传图片到网络
        loadPicToNet(b, picturePath);

    }

    /**
     * 上传图片
     *
     * @param b 图片
     * @param picturePath 该图片的地址
     */
    private void loadPicToNet(Bitmap b, String picturePath) {

        // 先移除用来添加的图标，再添加以保证添加的图片始终在最后
        bitmapList.remove(addBitmapDeail);
        //上传成功后再添加图片
        bitmapList.add(new BitmapDetail(b, picturePath));

        //如果有效图片小于9张 就添加 + 号图片, 并上传
        if(bitmapList.size() < 9) {
            bitmapList.add(addBitmapDeail);
        }
        //
        imageAdapter.setBitmapsDetail(bitmapList);
        imageAdapter.notifyDataSetChanged();

    }


    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        //
        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }


    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }


    /**
     * 放弃编辑
     */
    private void abandonEdit() {

        new AlertDialog.Builder(this).setMessage("要放弃本次编辑吗").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        }).show();

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                abandonEdit();

                break;

        }
        return super.onKeyDown(keyCode, event);
    }
}
